package com.base.core.devtools.utils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.core.utils.codec.Md5;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerUtils {

	public static <T>String fill(String prompt,Map<String,T> params) {
    	Configuration configuration = new Configuration(Configuration.VERSION_2_3_33);
    	Template template;
		try (Reader reader = new StringReader(prompt)) {
			template = new Template(Md5.md5(prompt),reader, configuration);
        }catch (IOException e) {
			throw new ApplicationException(e);
		}
    	StringWriter sw=new StringWriter();
    	try {
			template.process(params, sw);
		} catch (Exception e) {
			throw new ApplicationException(e);
		}
    	return sw.toString();
	}
	
	public static void main(String[] args) {
    	Map<String,Object> dataModel = new HashMap<>();
    	dataModel.put("hello", "this is my first freemarker test.");
    	dataModel.put("frecvDate", new Date());
    	dataModel.put("tt1", "te");
    	dataModel.put("name", "te");
    	String content="""
    			fjdksjfldjf ${hello} flkdjsalkfjdls哈哈哈要
    			${frecvDate?string('yyyy-MM-dd')}
    			<#if tt1??>
    			这是王者${tt1}
    			</#if>
    			${name}
    			""";
    	String c=FreemarkerUtils.fill(content, dataModel);
    	System.out.println(c);
	}
	
}
